#!/usr/bin/bash

# tmuxrestore v0.1.0
# load $HOME/.tmux/tmuxsession_\$SESSION.windows to restore tmux session
# Copyright by calvin 2021

function usage()
{
	echo "USAGE : tmuxrestore [ session ]"
	exit 1
}

if [ $# -eq 1 ] && [ x"$1" = x"?" ] ; then
	usage
	exit 1
elif [ $# -gt 1 ] ; then
	usage
	exit 1
fi

STORE_SESSION=$1
if [ x"$STORE_SESSION" = x"-l" ] ; then
	STORE_SESSION=""
	LIST_ONLY=1
else
	LIST_ONLY=0
fi

if [ ! -d $HOME/.tmux ] ; then
	mkdir -p $HOME/.tmux
fi

if [ x"$STORE_SESSION" = x"" ] ; then
	STORE_SESSION=*
fi

ls -1 $HOME/.tmux/tmuxsession_${STORE_SESSION}.windows | while read STORE_FILE ; do
	STORE_SESSION=`basename ${STORE_FILE} .windows | awk -F_ '{print $2}'`
	if [ $LIST_ONLY -eq 1 ] ; then
		echo "session \"${STORE_SESSION}\" found"
		continue
	fi
	
	tmux new-session -s ${STORE_SESSION} -d
	if [ $? -eq 0 ] ; then
		echo "session \"${STORE_SESSION}\" restored"
	else
		echo "ERROR : session \"${STORE_SESSION}\" restoring failed"
		exit 1
	fi
	
	cat ${STORE_FILE} | while read FILE_LINE ; do
		WINDOW_INDEX=`echo ${FILE_LINE} | awk '{print $1}'`
		WINDOW_CURRENT_PATH=`echo ${FILE_LINE} | awk '{print $2}'`
		tmux new-window -t "${STORE_SESSION}:${WINDOW_INDEX}" -c "${WINDOW_CURRENT_PATH}" -k
		if [ $? -eq 0 ] ; then
			echo "session \"${STORE_SESSION}\" window \"${WINDOW_INDEX}\" path \"${WINDOW_CURRENT_PATH}\" restored"
		else
			echo "ERROR : session \"${STORE_SESSION}\" window \"${WINDOW_INDEX}\" path \"${WINDOW_CURRENT_PATH}\" restoring failed"
			exit 1
		fi
	done
done

